package com.txc.pay.alipayLife.service.impl;

import cn.hutool.json.JSONUtil;
import com.txc.openfeign.common.pay.api.PayBusinessApi;
import com.txc.openfeign.common.pay.dto.CollectDto;
import com.txc.openfeign.common.pay.dto.CostInfoDto;
import com.txc.openfeign.common.pay.vo.ResBaseVO;
import com.txc.openfeign.common.pay.vo.ResponseCodeEnum;
import com.txc.openfeign.common.pay.vo.UserCostInfoVO;
import com.txc.common.utils.pay.CommonUtil;
import com.txc.pay.alipayLife.service.AliPayLifeService;
import com.txc.pay.alipayLife.utils.SftpUtil;
import com.txc.pay.entity.PayLogEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.io.*;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 支付宝生活缴费
 *
 * @ProjectName smartWater-admin
 * @Description TODO
 * @Author tao
 * @Date 2023-06-19
 * @Version 1.0
 */
@Service
public class AliPayLifeServiceImpl implements AliPayLifeService {
    private static final Logger logger = LoggerFactory.getLogger(AliPayLifeServiceImpl.class);

    @Resource
    private PayBusinessApi payBusinessApi;

    @Value(value = "${lifePay.localPath}")
    public String localPath;

    @Value("${lifePay.life.acctOrgNo}")
    private String acctOrgNo;

    /**
     * 开始对账
     */
    @Override
    public void reconciliation(String filePath, String fileName) {
        // 执行sftp，下载文件
        SftpUtil sftpUtil = new SftpUtil();
        // 连接
        sftpUtil.connect();
        boolean downFlag;// 是否下载失败
        // sftp下载文件
        try {
            downFlag = sftpUtil.downloadFile(filePath, fileName, localPath, fileName);
        } catch (Exception e) {
            logger.error("对账文件下载失败！{}", e.getMessage());
            throw new RuntimeException(e);
        }
        if (!downFlag) {
            logger.error("对账文件下载失败！");
            return;
        }
        logger.info("支付宝生活缴费：对账文件下载完成！");
        // 打开文件
        String localFilePath = localPath + File.separator + fileName;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(localFilePath);
        } catch (FileNotFoundException e) {
            logger.info("错误{}", e.getMessage());
        }
        assert fileInputStream != null;
        InputStreamReader reader = new InputStreamReader(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(reader);
        try {
            fileInputStream.close();
            bufferedReader.close();
        } catch (IOException e) {
            logger.info("错误{}", e.getMessage());
        }
    }

    @Override
    public ResBaseVO aliPayFallBack(Map<String, Object> head, Map<String, Object> body) {
        ResBaseVO resVo = null;
        String servCode = head.get("servCode").toString().replace("\"", "");
        switch (servCode) {
            case "200001": //5.1.2 ①欠费查询接口规范
                resVo = getUserCostInfo(body);
                break;
            case "200002": //5.1.3②代收缴费接口规范
                resVo = collect(body);
                break;
            case "200012": //5.2.2④销账结果查询接口规范
                resVo = queryPayment(body);
                break;
            case "200011": //5.3.3文件通知接口规范 公用事业平台发起文本推送时调用此接口
                resVo = noticeCheck(body);
                break;
        }
        return resVo;
    }

    private ResBaseVO getUserCostInfo(Map<String, Object> body) {
        UserCostInfoVO costInfoVO = payBusinessApi.getUserCostInfo(CostInfoDto.getInstance(body));
        costInfoVO.setAcctOrgNo(acctOrgNo);
        return costInfoVO;
    }

    private ResBaseVO collect(Map<String, Object> body) {
        CollectDto param = CollectDto.getInstance(body);
        ResBaseVO resBaseVO = payBusinessApi.collect(param);
        LocalDateTime now = LocalDateTime.now();
        PayLogEntity entity = new PayLogEntity();
        entity.setPayTime(now);
        entity.setTotalFee(param.getRcvAmt());
        entity.setTransactionId(param.getBankSerial());
        entity.setAttr(JSONUtil.toJsonStr(param));
        entity.setServId(param.getRcvDet().get(0).getConsNo());
        entity.setCreateTime(now);
        entity.setUpdateTime(now);
        if (ResponseCodeEnum.CODE_9999.getValue().equals(resBaseVO.getRtnCode())) {
            entity.setStatus("1");
        }
        entity.setUpdateTime(now);
        entity.insert();
        return resBaseVO;
    }

    private ResBaseVO queryPayment(Map<String, Object> body) {
        String acctOrgNo = CommonUtil.getStrByBody(body, "acctOrgNo");
        String bankSerial = CommonUtil.getStrByBody(body, "bankSerial");
        String bankDate = CommonUtil.getStrByBody(body, "bankDate");
        return payBusinessApi.queryPayment(bankSerial, bankDate, acctOrgNo);
    }

    private ResBaseVO noticeCheck(Map<String, Object> body) {
        String acctOrgNo = CommonUtil.getStrByBody(body, "acctOrgNo");
        String filePath = CommonUtil.getStrByBody(body, "filePath");
        String fileType = CommonUtil.getStrByBody(body, "fileType");
        String fileName = CommonUtil.getStrByBody(body, "fileName");
        logger.info("有文件通知——filePath: {}, fileName: {}", filePath, fileName);
        return payBusinessApi.noticeCheck(acctOrgNo, filePath, fileType, fileName);
    }


    /**
     * 判断字符串是否相等
     */
    private boolean compareStr(String str, String str2) {
        return (str == null && str2 == null) || (str != null && str.equals(str2));
    }
}
